<template>
	<view class="root">
		<u-row gutter="16" style="padding-top: 20rpx;">
			<u-col span="3">
				<u-search height="25" :disabled="this.active!==3" @custom="search" @click="toSearch()"
					v-model="keyword"></u-search>
			</u-col>
			<u-col span="1">
				<view class="item" :class="active==1?'active':''" @click="changeStatus(1)">推荐</view>
			</u-col>
			<u-col span="1">
				<view class="item" :class="active==2?'active':''" @click="changeStatus(2)">更新</view>
			</u-col>
		</u-row>
		<u-loading-icon :show="loading" style="margin-top: 50rpx;"></u-loading-icon>
		<template v-if="!loading">
			<view v-if="active==1">
				<u-row gutter="16" style="margin-top: 20rpx;">
					<u-col span="4" v-for="(i,index) in recommendApp" :class="`img${index} bgImg`">
						<u-col span="9" style="flex-direction: row; margin: 15rpx 0 0 5rpx; flex: 0 0 55%;">
							<u-image width="50rpx" height="50rpx" :src="BaseUrl+i.appIcon"></u-image>
							<u-col>
								<u-text :text="i.appName" bold style="flex: 0;"></u-text>
								<u-text :text="i.appDescription" lines="2" style="flex: 0;" size="10"
									color="gray"></u-text>
							</u-col>
						</u-col>
						<u-col span="3">
							<u-button
								:loading="downloadingAppIds.includes(i.id)"
								:text="downloadingAppIds.includes(i.id) ? '' : getAppStatus(i)"
								:color="getAppStatus(i, true)"
								:disabled="getAppStatus(i) == '已安装'"
								@click="handleDownload(i, getAppStatus(i))"
								style="width: 70rpx;height: 30rpx;border-radius: 5rpx;"></u-button>
						</u-col>
					</u-col>
				</u-row>
				<u-text text="本周热门" bold margin="10rpx 0"></u-text>
				<u-row>
					<u-col span="4" style="flex-direction: row; align-items: center;" v-for="i in tipicApp">
						<u-image width="40rpx" height="40rpx" :src="BaseUrl+i.appIcon"></u-image>
						<u-col span="9" style="padding-left: 5rpx; flex:0 0 55%;">
							<u-text :text="i.appName"></u-text>
							<u-col style="flex-direction: row; padding: 0;">
								<u-text :text="'发布版本：' + i.appVersion" color="gray" size="7"></u-text>
								<u-text :text="'下载次数：' + (i.downloadCount || 0)" color="gray" size="7"></u-text>
							</u-col>
						</u-col>
						<u-col span="2">
							<u-button
								:loading="downloadingAppIds.includes(i.id)"
								:text="downloadingAppIds.includes(i.id) ? '' : getAppStatus(i)"
								:color="getAppStatus(i, true)"
								:disabled="getAppStatus(i) == '已安装'"
								@click="handleDownload(i, getAppStatus(i))"
								style="width: 50rpx;height: 20rpx;border-radius: 5rpx;"></u-button>
						</u-col>
					</u-col>
				</u-row>
			</view>
			<view v-if="active==2||active==3">
				<u-row style="flex-wrap: wrap;">
					<u-col span="4" style="flex-direction: row; align-items: center;margin: 15rpx 0;" v-for="i in show">
						<u-image width="40rpx" height="40rpx" :src="BaseUrl+i.appIcon"></u-image>
						<u-col span="9" style="padding-left: 5rpx; flex:0 0 55%;">
							<u-text :text="i.appName"></u-text>
							<u-col style="flex-direction: row; padding: 0;">
								<u-text :text="'发布版本：' + i.appVersion" color="gray" size="7"></u-text>
								<u-text :text="'下载次数：' + (i.downloadCount || 0)" color="gray" size="7"></u-text>
							</u-col>
						</u-col>
						<u-col span="2">
							<u-button 
								:loading="downloadingAppIds.includes(i.id)"
								:text="downloadingAppIds.includes(i.id) ? '' : getAppStatus(i)"
								:color="getAppStatus(i, true)"
								:disabled="getAppStatus(i) == '已安装'"
								@click="handleDownload(i, getAppStatus(i))"
								style="width: 50rpx;height: 20rpx;border-radius: 5rpx;">
							</u-button>
						</u-col>
					</u-col>
				</u-row>
			</view>
		</template>
		<bottom></bottom>
	</view>
</template>

<script>
	import bottom from '@/components/bottom/index.vue'
	import {
		getApplicationMarketList,
		getApplicationMarketTopicList,
		addApplicationMarketRecord
	} from "@/config/api/applicationMarket";
	export default {
		components: {
			bottom
		},
		data() {
			return {
				// 激活的tab页
				active: 1,
				// 所有app
				allApp: [],
				// 推荐App
				recommendApp: [],
				// 专题app
				tipicApp: [],
				BaseUrl: uni.$u.http.config.baseURL,
				//页面展示的app
				show: [],
				//需要更新的app
				updataApp: [],
				//搜索关键字
				keyword: "",
				loading: true,
				// 本机应用列表
				/*
				appName:应用名称
				packageName:应用包名
				versionName:应用版本名称
				versionCode:应用版本号
				*/
				installedAppList: [],
				// 正在下载的appId
				downloadingAppIds: [],
			}
		},
		onShow(){
			this.getApplicationMarketList()
			var that = this
			setTimeout(function(){
				that.loading = false
			},3000)
		},
		methods: {
			getApplicationMarketList(){
				getApplicationMarketList().then(res => {
					this.allApp = res.rows
					this.recommendApp = this.allApp.filter((item) => item.isRecommended).splice(0, 3);
					// 获取已安装的app
					this.getAppList().then(res => {
						this.installedAppList = res
						this.updataApp = this.allApp.filter((item) => {
							// installedAppList = 本地已安装的app 如果包名相同，版本号小于服务器版本号就是需要更新的
							const app = this.installedAppList.find((app) => app.packageName === item
								.appPackageName);
							// 找到了app并且版本号小于服务器版本号
							if (app) {
								return item.appVersion > app.versionName;
							}
							// 没找到就不需要更新
							return false;
						});
					})
				})
				getApplicationMarketTopicList().then(res => {
					this.tipicApp = res.rows[0].appList
				})
			},
			//切换tab页
			changeStatus(data) {
				this.active = data
				this.show = this.active == 1 ? this.allApp : this.updataApp
			},
			// 搜索
			search() {
				getApplicationMarketList({
					appName: this.keyword
				}).then(res => {
					this.show = res.rows
				})
			},
			toSearch(){
				this.active=3
				this.show = this.allApp
			},
			//获取已安装的app
			getAppList() {
				return new Promise((resolve, reject) => {
					// #ifdef APP-PLUS
					// 导入 Android 相关类
					plus.android.importClass('java.util.ArrayList');
					plus.android.importClass('android.content.pm.PackageInfo');
					plus.android.importClass('android.content.pm.PackageManager');
					// 获取主活动和包管理器
					let MainActivity = plus.android.runtimeMainActivity();
					let PackageManager = MainActivity.getPackageManager();
					// 获取已安装应用的包信息列表
					let pinfo = plus.android.invoke(PackageManager, 'getInstalledPackages', 0);
					if (pinfo != null) {
						let apklist = [];
						// 遍历已安装应用列表
						for (let i = 0; i < pinfo.size(); i++) {
							let pkginfo = pinfo.get(i);
							// 检查应用是否为系统应用
							let issysapk = ((pkginfo.plusGetAttribute("applicationInfo").plusGetAttribute(
									"flags") & plus.android.importClass(
									'android.content.pm.ApplicationInfo')
								.FLAG_SYSTEM) != 0) ? true : false;
							if (issysapk == false) {
								// 提取所需的信息（包名和版本号）
								const apkinfo = {
									packageName: pkginfo.plusGetAttribute("packageName"),
									versionName: pkginfo.plusGetAttribute("versionName")
								};
								apklist.push(apkinfo);
							}
						}
						// 使用已安装应用列表解析 Promise
						resolve(apklist);
					} else {
						// 如果已安装应用列表为空，则拒绝 Promise
						reject([]);
					}
					// #endif
					// #ifndef APP-PLUS
					// 如果不在 APP-PLUS 环境中运行，则解析为空数组
					resolve([]);
					// #endif
				});
			},
			getAppStatus(item, color = false) {
				//查找本机app中跟传入包名相同的app
				const app = this.installedAppList.find((app) => app.packageName === item.appPackageName);
				if (app) {
					if (color) {
						// 如果服务器版本号大于本地版本号就是需要更新的
						return item.appVersion > app.versionName ? "#00b4ff" : "#bdd6e1";
					}
					// 如果服务器版本号大于本地版本号就是需要更新的
					return item.appVersion > app.versionName ? "更新" : "已安装";
				}
				// 如果没有找到就是未安装,如果是颜色就返回黑色，否则返回下载
				if (color) {
					return "#000000";
				}
				return "下载";
			},
			//处理下载流程
			async handleDownload(item, status) {
				console.log(item);
				// 下载中的appId
				// #ifdef APP-PLUS
				this.downloadingAppIds.push(item.id);
				// #endif
				const result = await this.downAndInstallApp(this.BaseUrl, item.appUrl);
				if (result == 200) {
					// 下载完成的appId就从下载中的appId中移除
					this.downloadingAppIds = this.downloadingAppIds.filter((id) => id !== item.id);
					// 添加下载记录
					addApplicationMarketRecord({
						appId: item.id
					});
					// 重新获取列表
					this.getApplicationMarketList()
				};
			},
			//下载方法
			downAndInstallApp(url, path) {
				return new Promise((resolve, reject) => {
					// #ifdef APP-PLUS
					uni.showToast({
						title: '开始下载',
						icon: 'none'
					});
					uni.downloadFile({
						url: `${url}${path}`,
						success: (downloadResult) => {
							//force:true 强制覆盖已存在的同名应用程序
							plus.runtime.install(downloadResult.tempFilePath, {
								force: true
							}, function(widgetInfo) {}, function(error) {});
							resolve(downloadResult.statusCode)
						},
						fail: (error) => {
							reject(error)
						}
					});
					// #endif
					// #ifndef APP-PLUS
					uni.showToast({
						title: '请在app中打开',
						icon: 'none'
					});
					// #endif
				})
			}
		}
	}
</script>

<style scoped>
	.root {
		width: calc(100% - 70px);
		margin: 0 auto;
	}

	.item {
		font-size: 15rpx;
		text-align: center;
		font-weight: bold;
	}

	.active {
		color: #00b4ff;
		position: relative;
	}

	.active::after {
		content: "";
		position: absolute;
		width: 65%;
		height: 4px;
		border-radius: 9px;
		/* 渐变 左到右 #00f1ff #00b4ff*/
		background: linear-gradient(to right, #00f1ff, #00b4ff);
		bottom: -5px;
		left: 15%;
	}

	.img0 {
		background: url("@/static/card_bg1.png");
	}

	.img1 {
		background: url("@/static/card_bg2.png");
	}

	.img2 {
		background: url("@/static/card_bg3.png");
	}

	.bgImg {
		height: 120rpx;
		background-size: 100% 100%;
		background-repeat: no-repeat;
	}
</style>